package com.video.moderation.service.impl;

import com.video.moderation.constant.SecurityConstants;
import com.video.moderation.entity.SysMember;
import com.video.moderation.entity.dto.Result;
import com.video.moderation.exception.ServiceException;
import com.video.moderation.repository.SysMemberRepository;
import com.video.moderation.service.SysMemberService;
import com.video.moderation.utils.IpUtils;
import com.video.moderation.utils.JwtUtils;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.mindrot.jbcrypt.BCrypt;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
@Transactional
public class SysMemberServiceImpl implements SysMemberService {

    @Autowired
    private SysMemberRepository sysMemberRepository;

    @Resource
    private JwtUtils jwtUtils;

    @Override
    public Result login(String memberNum, String password, HttpServletRequest request, HttpServletResponse response) {
        SysMember member = sysMemberRepository.findSysMemberByAccount(memberNum);
        if (member == null) throw new ServiceException("工号或密码错误");

        if (!BCrypt.checkpw(password, member.getPassword())) throw new ServiceException("工号或密码错误");
        
        if (!member.getRole().equals("客服审核员")) throw new ServiceException("权限不足，无法访问");

        String token = jwtUtils.generateJwtToken(member.getMemberId(), memberNum);
        response.setHeader(SecurityConstants.AUTHORIZATION, token);
        response.setHeader("Access-control-Expost-Headers", SecurityConstants.AUTHORIZATION);
        Map<String, Object> map = new HashMap<>();
        map.put("token", token);
        map.put("memberId", member.getMemberId());
        map.put("memberNum", member.getMemberNum());

        // 记录登录时间和IP
        member.setLoginTime(new Date());
        member.setLoginIp(IpUtils.getClientIP(request));
        return Result.success("登录成功", map);
    }
}
